package server;

import classLoader.MyClassLoader;
import mapper.Context;
import mapper.Host;
import mapper.Mapper;
import mapper.Wrapper;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    private static Map<String, Host> hostMap = new HashMap<>();

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
        loadServlet();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat_work start on port：" + port);

        while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, hostMap);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }



    }

    /**
     * 加载解析web.xml，初始化Servlet
     * 作业部分：解析server.xml文件
     */
    private void loadServlet() {

        SAXReader saxReader = new SAXReader();

        try {
            // 作业开始-----------------------------------------------------------------------------------
            // 1. 获取server.xml文件流
            InputStream serverInputStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
            // 2. 使用Dom4j解析文件流
            Document serverDocument = saxReader.read(serverInputStream);
            // 3. 读取Service标签（此次作业以一个Service为准），获取端口
            Element node = (Element) serverDocument.selectSingleNode("//Connector");
            port = Integer.parseInt(node.attributeValue("port"));
            // 4. 读取Host标签，获取域名和webapps路径
            Map<String, Host> hostMap = new Mapper().getHostMap();
            List<Element> list = serverDocument.selectNodes("//Host");
            for (Element element : list) {
                String hostName = element.attributeValue("name"); // localhost
                String webappPath = element.attributeValue("appBase");
                Host host = new Host();
                host.setName(hostName);
                host.setAppBase(webappPath);
                hostMap.put(hostName, host);
                // 5. 拿到webapps路径后，找到该目录下所有的web应用，封装成Context
                File file = new File(webappPath); // D:\IdeaProject\study\gaoxin\phase2_1\Minicat\webapps
                File[] allFiles = file.listFiles();
                if (allFiles != null && allFiles.length != 0) {
                    for (File dirFile : allFiles) {
                        if (dirFile.isDirectory()) {
                            Context context = new Context();
                            context.setPath("/" + dirFile.getName());
                            host.getContextMap().put("/" + dirFile.getName(), context);
                            // 6. 找到web应用下的web.xml配置文件进行解析，找到Servlet并封装成Wrapper
                            parseWebXml(dirFile.getAbsolutePath(), context);

                        }
                    }
                }
            }
            // 7. 最后将HostMap封装到Mapper中
            this.hostMap = hostMap;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void parseWebXml(String fileName, Context context) throws Exception {

        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read(new FileInputStream(fileName + File.separator + "WEB-INF" + File.separator + "web.xml"));
        Element rootElement = document.getRootElement();

        /*HashMap map = new HashMap();
        map.put("design",rootElement.getNamespaceURI());
        // 创建解析路径，就是在普通的解析路径前加上map里的key值
        XPath xPath = document.createXPath("//design:web-app/design:servlet");
        xPath.setNamespaceURIs(map);
        List selectNodes = xPath.selectNodes(document);*/

        List<Element> selectNodes = rootElement.elements("servlet");
        for (int i = 0; i < selectNodes.size(); i++) {
            Element element =  selectNodes.get(i);
            // <servlet-name>lagou</servlet-name>
            Element servletnameElement = element.element("servlet-name");
            String servletName = servletnameElement.getStringValue();
            // <servlet-class>server.LagouServlet</servlet-class>
            Element servletclassElement = element.element("servlet-class");
            String servletClass = servletclassElement.getStringValue(); // com.zzw.servlet.DemoServlet


            // 根据servlet-name的值找到url-pattern
            List<Element> servletMapping =  rootElement.elements("servlet-mapping");
            for (Element element1 : servletMapping) {
                Element element2 = element1.element("servlet-name");
                if (servletName.equals(element2.getStringValue())) {

                    Element element3 = element1.element("url-pattern");
                    String urlPattern = element3.getStringValue(); //  /demo

                    // 获取servlet的绝对路径 D:\IdeaProject\study\gaoxin\phase2_1\Minicat_work\webapps\WEB_INF\classes\com.zzw.servlet.DemoServlet
                    String absolutePath = fileName + File.separator + "WEB-INF" + File.separator + "classes" + File.separator + servletClass;
                    // D:\IdeaProject\study\gaoxin\phase2_1\Minicat_work\webapps\WEB_INF\classes\com\zzw\servlet\DemoServlet.class
                    absolutePath = absolutePath.replace(".", File.separator) + ".class";

                    HttpServlet servlet = (HttpServlet) (new MyClassLoader(absolutePath).loadClass(servletClass)).newInstance();
                    Wrapper wrapper = new Wrapper();
                    wrapper.setServlet(servlet);

                    // 封装Wrapper
                    context.getWrapperMap().put(urlPattern, wrapper);
                }
            }


        }

    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
